/**
 * 文档处理工具 JavaScript
 */
document.addEventListener('DOMContentLoaded', () => {
    // 添加调试语句，确认新版本已加载
    console.log('文档处理工具 - 新版本已加载 - 带浮动进度条');
    
    // 检查登录状态，如果未登录则重定向到登录页
    if (!sessionStorage.getItem('isLoggedIn') || !sessionStorage.getItem('jwtToken')) {
        console.log('未检测到登录状态或JWT令牌，重定向到登录页面');
        window.location.href = 'login.html';
        return;
    }
    
    // 初始化会话过期处理
    initSessionExpirationHandler();
    
    // DOM元素
    const docDropZone = document.getElementById('docDropZone');
    const docFileInput = document.getElementById('docFileInput');
    const fileList = document.getElementById('fileList');
    const processAndDownloadButton = document.getElementById('processAndDownloadButton');
    const progressArea = document.getElementById('progressArea');
    const progressBar = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    const statusText = document.getElementById('statusText');
    const resultArea = document.getElementById('resultArea');
    const downloadBtn = document.getElementById('downloadBtn');
    const viewResultBtn = document.getElementById('viewResultBtn');
    const analysisArea = document.getElementById('analysisArea');
    const analysisResult = document.getElementById('analysisResult');
    const loadingOverlay = document.getElementById('loadingOverlay');
    const loadingText = document.getElementById('loadingText');
    const errorModal = document.getElementById('errorModal');
    const errorMessage = document.getElementById('errorMessage');
    const closeErrorModal = document.getElementById('closeErrorModal');
    const statusModal = document.getElementById('statusModal');
    const statusIcon = document.getElementById('statusIcon');
    const statusTitle = document.getElementById('statusTitle');
    const javaStatus = document.getElementById('javaStatus');
    const pythonStatus = document.getElementById('pythonStatus');
    const overallStatus = document.getElementById('overallStatus');
    const closeStatusModal = document.getElementById('closeStatusModal');
    const sessionExpiredModal = document.getElementById('sessionExpiredModal');
    const redirectTimer = document.getElementById('redirectTimer');
    const importantNoticeModal = document.getElementById('importantNoticeModal');
    const closeImportantNoticeModal = document.getElementById('closeImportantNoticeModal');

    // 文件数据
    let currentFile = null;
    let originalFilename = null; // 保存原始文件名
    let processedResult = null;
    let downloadUrl = null;
    
    // 初始化 - 检查服务状态
    checkServiceStatus();

    // 为DOM元素添加事件监听器，但先确保它们存在
    if (docDropZone) {
        // 上传区域拖放功能
        docDropZone.addEventListener('click', () => docFileInput.click());
        
        docDropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            docDropZone.classList.add('dragover');
        });
        
        docDropZone.addEventListener('dragleave', () => {
            docDropZone.classList.remove('dragover');
        });
        
        docDropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            docDropZone.classList.remove('dragover');
            
            if (e.dataTransfer.files.length) {
                handleFileUpload(e.dataTransfer.files[0]);
            }
        });
    } else {
        console.error('上传区域元素不存在');
    }
    
    // 文件输入事件
    if (docFileInput) {
        docFileInput.addEventListener('change', (e) => {
            if (e.target.files.length) {
                handleFileUpload(e.target.files[0]);
            }
        });
    } else {
        console.error('文件输入元素不存在');
    }
    
    // 处理并下载按钮点击事件
    if (processAndDownloadButton) {
        processAndDownloadButton.addEventListener('click', () => {
            console.log('处理并下载按钮被点击');
            if (currentFile) {
                // 显示浮动进度条并立即更新到第一阶段
                const floatingProgress = document.getElementById('floatingProgress');
                if (floatingProgress) {
                    console.log('显示浮动进度条');
                    floatingProgress.style.display = 'block';
                    setTimeout(() => {
                        floatingProgress.classList.add('visible');
                    }, 10);
                } else {
                    console.error('未找到浮动进度条元素');
                }
                
                // 处理文档
                processDocument(true);
            } else {
                console.warn('没有选择文件，无法处理');
            }
        });
    } else {
        console.error('处理按钮元素不存在');
    }
    
    // 下载按钮点击事件
    if (downloadBtn) {
        downloadBtn.addEventListener('click', () => {
            if (downloadUrl) {
                window.location.href = downloadUrl;
            }
        });
    }
    
    // 查看结果按钮点击事件
    if (viewResultBtn && analysisResult && analysisArea) {
        viewResultBtn.addEventListener('click', () => {
            if (processedResult) {
                analysisResult.textContent = JSON.stringify(processedResult, null, 2);
                analysisArea.classList.remove('hidden');
                // 滚动到分析结果区域
                analysisArea.scrollIntoView({ behavior: 'smooth' });
            }
        });
    }
    
    // 关闭错误模态框
    if (closeErrorModal) {
        closeErrorModal.addEventListener('click', () => {
            if (errorModal) errorModal.classList.add('hidden');
        });
    }
    
    // 关闭状态模态框
    if (closeStatusModal) {
        closeStatusModal.addEventListener('click', () => {
            if (statusModal) statusModal.classList.add('hidden');
        });
    }

    // 确保关闭按钮可以点击 - 修复事件委托问题
    document.addEventListener('click', (e) => {
        // 处理状态模态框关闭按钮
        if (e.target.id === 'closeStatusModal' || e.target.closest('#closeStatusModal')) {
            statusModal.classList.add('hidden');
        }
        
        // 处理错误模态框关闭按钮
        if (e.target.id === 'closeErrorModal' || e.target.closest('#closeErrorModal')) {
            errorModal.classList.add('hidden');
        }
        
        // 处理服务繁忙提示框关闭按钮
        if (e.target.id === 'closeServiceBusyBtn' || e.target.closest('#closeServiceBusyBtn')) {
            resultArea.classList.add('hidden');
        }
    });

    /**
     * 初始化会话过期处理
     */
    function initSessionExpirationHandler() {
        // 定期检查令牌有效性
        const tokenCheckInterval = setInterval(() => {
            if (!sessionStorage.getItem('jwtToken')) {
                clearInterval(tokenCheckInterval);
                showSessionExpiredModal();
                return;
            }
            
            // 每分钟检查一次令牌有效性
            fetch('/api/status', {
                headers: {
                    'Authorization': `Bearer ${sessionStorage.getItem('jwtToken')}`
                }
            })
            .then(response => {
                if (response.status === 401 || response.status === 403) {
                    clearInterval(tokenCheckInterval);
                    throw new Error('令牌已过期');
                }
                return response.json();
            })
            .catch(error => {
                console.error('令牌检查失败:', error);
                clearInterval(tokenCheckInterval);
                showSessionExpiredModal();
            });
        }, 60000); // 每分钟检查一次
    }
    
    /**
     * 显示会话过期模态框
     */
    function showSessionExpiredModal() {
        if (!sessionExpiredModal) return;
        
        // 先确保正确获取重新登录按钮元素
        const reloginBtn = document.getElementById('reloginBtn');
        
        // 清除可能存在的旧事件监听器
        if (reloginBtn) {
            const newReloginBtn = reloginBtn.cloneNode(true);
            reloginBtn.parentNode.replaceChild(newReloginBtn, reloginBtn);
            
            // 重新添加事件监听器
            newReloginBtn.addEventListener('click', function() {
                console.log('重新登录按钮被点击');
                // 清除会话存储
                sessionStorage.removeItem('isLoggedIn');
                sessionStorage.removeItem('jwtToken');
                // 立即重定向到登录页面
                window.location.href = 'login.html';
            });
        }
        
        // 显示模态框
        sessionExpiredModal.classList.remove('hidden');
        
        // 倒计时重定向
        let countdown = 5;
        const countdownInterval = setInterval(() => {
            if (redirectTimer) {
                redirectTimer.textContent = `${countdown}秒后自动跳转至登录页面...`;
            }
            
            countdown--;
            
            if (countdown < 0) {
                clearInterval(countdownInterval);
                // 清除会话存储
                sessionStorage.removeItem('isLoggedIn');
                sessionStorage.removeItem('jwtToken');
                // 重定向到登录页面
                window.location.href = 'login.html';
            }
        }, 1000);
    }

    /**
     * 处理文件上传
     */
    function handleFileUpload(file) {
        // 检查文件类型
        const fileType = file.name.toLowerCase().split('.').pop();
        if (fileType !== 'doc' && fileType !== 'docx') {
            showError('只支持Word文档(.doc, .docx)格式');
            return;
        }
        
        // 检查文件大小 (20MB限制)
        if (file.size > 20 * 1024 * 1024) {
            showError('文件大小不能超过20MB');
            return;
        }
        
        // 保存当前文件和原始文件名
        currentFile = file;
        originalFilename = file.name;
        
        // 更新文件列表显示
        fileList.innerHTML = '';
        const fileItem = document.createElement('div');
        fileItem.className = 'file-item flex items-center justify-between bg-gray-50 p-3 rounded-lg border border-gray-200';
        fileItem.innerHTML = `
            <div class="flex items-center">
                <div class="p-2 bg-blue-100 rounded-md mr-3">
                    <i class="fas fa-file-word text-blue-600"></i>
                </div>
                <div>
                    <p class="text-sm font-medium text-gray-900">${file.name}</p>
                    <p class="text-xs text-gray-500">${formatFileSize(file.size)}</p>
                </div>
            </div>
            <button class="remove-file text-gray-400 hover:text-red-500">
                <i class="fas fa-times"></i>
            </button>
        `;
        
        // 添加删除按钮事件
        const removeBtn = fileItem.querySelector('.remove-file');
        removeBtn.addEventListener('click', () => {
            fileList.innerHTML = '';
            currentFile = null;
            updateButtonState();
        });
        
        fileList.appendChild(fileItem);
        
        // 更新按钮状态
        updateButtonState();
    }
    
    /**
     * 处理文档
     */
    function processDocument(downloadImmediately) {
        if (!currentFile) return;
        
        console.log('processDocument函数被调用:', {
            downloadImmediately,
            fileSize: currentFile ? currentFile.size : 'no file',
            fileName: currentFile ? currentFile.name : 'no file'
        });
        
        // 检查JWT令牌
        if (!sessionStorage.getItem('jwtToken')) {
            showSessionExpiredModal();
            return;
        }
        
        // 重置状态
        resetUI();
        
        // 确保浮动进度条显示
        const floatingProgress = document.getElementById('floatingProgress');
        if (floatingProgress) {
            console.log('显示浮动进度条 - processDocument内');
            floatingProgress.style.display = 'block';
            setTimeout(() => {
                floatingProgress.classList.add('visible');
            }, 10);
        } else {
            console.error('未找到浮动进度条元素 - processDocument内');
        }
        
        // 显示进度区域（保留这行，因为可能有其他逻辑依赖它）
        if (progressArea) progressArea.classList.remove('hidden');
        
        // 显示浮动进度条并更新到第一阶段
        updateProgress(5, '准备处理...', 1);
        
        // 创建FormData
        const formData = new FormData();
        formData.append('file', currentFile);
        
        // 添加原始文件名作为表单字段
        formData.append('originalFilename', originalFilename);
        
        // 选择API端点
        const endpoint = downloadImmediately ? '/api/process-and-download' : '/api/process';
        
        // 获取JWT令牌
        const token = sessionStorage.getItem('jwtToken');
        
        // 发送请求
        if (downloadImmediately) {
            // 处理并下载 - 移除加载遮罩显示，改用浮动进度条来显示状态
            
            // 添加进度模拟
            let currentProgress = 5;
            const progressInterval = setInterval(() => {
                // 模拟进度增加，最多到95%
                if (currentProgress < 95) {
                    // 根据当前进度决定增加速度
                    let increment = 0;
                    if (currentProgress < 20) {
                        // 上传阶段 - 快速增加
                        increment = 3;
                        updateProgress(currentProgress, '上传文件...', 1);
                    } else if (currentProgress < 50) {
                        // 解析阶段 - 中速增加
                        increment = 2;
                        updateProgress(currentProgress, '解析内容...', 2);
                    } else if (currentProgress < 80) {
                        // 处理阶段 - 慢速增加
                        increment = 1;
                        updateProgress(currentProgress, '处理格式...', 3);
                    } else {
                        // 生成阶段 - 很慢增加
                        increment = 0.5;
                        updateProgress(currentProgress, '生成文档...', 4);
                    }
                    currentProgress += increment;
                    updateProgress(Math.min(Math.round(currentProgress), 95), null, Math.floor(currentProgress / 25) + 1);
                }
            }, 300);
            
            // 调试信息
            console.log('准备发送请求:', {
                endpoint: endpoint,
                method: 'POST',
                token: token ? '有效' : '无效',
                file: {
                    name: currentFile.name,
                    size: currentFile.size,
                    type: currentFile.type
                }
            });
            
            fetch(endpoint, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`
                },
                body: formData
            })
            .then(async response => {
                // 清除进度模拟
                clearInterval(progressInterval);
                
                // 检查响应类型
                const contentType = response.headers.get('content-type');
                
                if (response.status === 401 || response.status === 403) {
                    showSessionExpiredModal();
                    throw new Error('登录已过期');
                }
                
                if (response.status === 503) {
                    const data = await response.json();
                    showServiceBusyMessage(data.error || '系统正在为其他用户处理文档，请稍后再试');
                    throw new Error('服务繁忙');
                }
                
                if (!response.ok) {
                    // 尝试解析错误响应
                    let errorMessage = '处理失败';
                    try {
                        if (contentType && contentType.includes('application/json')) {
                            const data = await response.json();
                            errorMessage = data.error || errorMessage;
                        } else {
                            const text = await response.text();
                            console.error('服务器返回了非JSON响应:', text);
                            errorMessage = '服务器返回了无效的响应格式';
                        }
                    } catch (e) {
                        console.error('解析错误响应失败:', e);
                    }
                    throw new Error(errorMessage);
                }
                
                // 处理成功响应
                if (contentType && contentType.includes('application/octet-stream')) {
                    const contentDisposition = response.headers.get('content-disposition');
                    const filenameMatch = contentDisposition ? contentDisposition.match(/filename="?([^"]+)"?/) : null;
                    const serverFilename = filenameMatch ? filenameMatch[1] : 'processed-document.docx';
                    
                    // 基于原始文件名创建新的文件名
                    const filename = createProcessedFilename(originalFilename);
                    
                    // 下载文件
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                    
                    // 更新进度和显示成功
                    updateProgress(100, '处理并下载完成', 4);
                    setTimeout(() => {
                        progressArea.classList.add('hidden');
                        showSuccess();
                    }, 1000);
                } else if (contentType && contentType.includes('application/json')) {
                    // 处理JSON响应
                    const data = await response.json();
                    if (data.error) {
                        throw new Error(data.error);
                    }
                    processedResult = data;
                    updateProgress(100, '处理完成', 4);
                    setTimeout(() => {
                        progressArea.classList.add('hidden');
                        showSuccess();
                    }, 1000);
                } else {
                    throw new Error('服务器返回了无效的响应格式');
                }
            })
            .catch(error => {
                // 清除进度模拟
                clearInterval(progressInterval);
                
                console.error('处理文档时出错:', error);
                
                if (error.message === '登录已过期') {
                    progressArea.classList.add('hidden');
                    return;
                }
                
                showError(error.message || '处理文档时出错');
                progressArea.classList.add('hidden');
            });
        } else {
            // 仅处理
            // 添加进度模拟
            let currentProgress = 5;
            const progressInterval = setInterval(() => {
                // 模拟进度增加，最多到95%
                if (currentProgress < 95) {
                    currentProgress += Math.random() * 3;
                    updateProgress(Math.min(Math.round(currentProgress), 95), null, Math.floor(currentProgress / 25) + 1);
                }
            }, 300);
            
            updateProgress(10, '上传文件...', 1);
            
            fetch(endpoint, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`
                },
                body: formData
            })
            .then(async response => {
                // 清除进度模拟
                clearInterval(progressInterval);
                
                const contentType = response.headers.get('content-type');
                
                if (response.status === 401 || response.status === 403) {
                    showSessionExpiredModal();
                    throw new Error('登录已过期');
                }
                
                if (response.status === 503) {
                    const data = await response.json();
                    showServiceBusyMessage(data.error || '系统正在为其他用户处理文档，请稍后再试');
                    throw new Error('服务繁忙');
                }
                
                if (!response.ok) {
                    let errorMessage = '处理失败';
                    try {
                        if (contentType && contentType.includes('application/json')) {
                            const data = await response.json();
                            errorMessage = data.error || errorMessage;
                        } else {
                            const text = await response.text();
                            console.error('服务器返回了非JSON响应:', text);
                            errorMessage = '服务器返回了无效的响应格式';
                        }
                    } catch (e) {
                        console.error('解析错误响应失败:', e);
                    }
                    throw new Error(errorMessage);
                }
                
                if (!contentType || !contentType.includes('application/json')) {
                    throw new Error('服务器返回了无效的响应格式');
                }
                
                const data = await response.json();
                if (data.error) {
                    throw new Error(data.error);
                }
                
                processedResult = data;
                downloadUrl = data.downloadUrl;
                
                // 如果下载URL包含文件名，使用原始文件名构建新的下载URL
                if (downloadUrl && downloadUrl.includes('/download/')) {
                    try {
                        const baseUrlParts = downloadUrl.split('/');
                        baseUrlParts.pop();
                        const baseUrl = baseUrlParts.join('/');
                        const processedFilename = createProcessedFilename(originalFilename);
                        downloadUrl = baseUrl + '/' + encodeURIComponent(processedFilename);
                    } catch (e) {
                        console.error('处理下载URL时出错:', e);
                    }
                }
                
                // 自动触发下载
                if (downloadUrl) {
                    window.location.href = downloadUrl;
                }
                
                updateProgress(100, '处理完成', 4);
                setTimeout(() => {
                    progressArea.classList.add('hidden');
                    showSuccess();
                }, 1000);
            })
            .catch(error => {
                // 清除进度模拟
                clearInterval(progressInterval);
                
                console.error('处理文档时出错:', error);
                
                if (error.message === '登录已过期') {
                    progressArea.classList.add('hidden');
                    return;
                }
                
                showError(error.message || '处理文档时出错');
                progressArea.classList.add('hidden');
            });
        }
    }
    
    /**
     * 检查服务状态
     */
    function checkServiceStatus() {
        const token = sessionStorage.getItem('jwtToken');
        
        fetch('/api/status', {
            headers: {
                'Authorization': token ? `Bearer ${token}` : ''
            }
        })
        .then(response => {
            if (response.status === 401 || response.status === 403) {
                // 未授权，令牌可能已过期
                showSessionExpiredModal();
                throw new Error('登录已过期');
            }
            return response.json();
        })
        .then(data => {
            const javaServiceStatus = data.javaService === 'online';
            const pythonServiceStatus = data.pythonService === 'online';
            const overallServiceStatus = data.status === 'healthy';
            
            if (!overallServiceStatus) {
                showStatusModal(javaServiceStatus, pythonServiceStatus, overallServiceStatus);
            }
        })
        .catch(error => {
            console.error('获取服务状态失败:', error);
            
            if (error.message === '登录已过期') {
                // 授权错误已在前面处理
                return;
            }
            
            showStatusModal(false, false, false);
        });
    }
    
    /**
     * 显示服务状态模态框
     */
    function showStatusModal(javaServiceStatus, pythonServiceStatus, overallServiceStatus) {
        if (javaServiceStatus) {
            javaStatus.textContent = '在线';
            javaStatus.className = 'text-sm font-medium text-green-600';
        } else {
            javaStatus.textContent = '离线';
            javaStatus.className = 'text-sm font-medium text-red-600';
        }
        
        if (pythonServiceStatus) {
            pythonStatus.textContent = '在线';
            pythonStatus.className = 'text-sm font-medium text-green-600';
        } else {
            pythonStatus.textContent = '离线';
            pythonStatus.className = 'text-sm font-medium text-red-600';
        }
        
        if (overallServiceStatus) {
            statusIcon.innerHTML = '<i class="fas fa-check-circle text-green-500"></i>';
            statusTitle.textContent = '服务状态正常';
            overallStatus.textContent = '健康';
            overallStatus.className = 'text-sm font-medium text-green-600';
        } else {
            statusIcon.innerHTML = '<i class="fas fa-exclamation-triangle text-yellow-500"></i>';
            statusTitle.textContent = '服务状态异常';
            overallStatus.textContent = '部分服务不可用';
            overallStatus.className = 'text-sm font-medium text-yellow-600';
        }
        
        statusModal.classList.remove('hidden');
    }
    
    /**
     * 显示加载中遮罩
     */
    function showLoading(message) {
        loadingText.textContent = message || '处理中，请稍候...';
        loadingOverlay.classList.remove('hidden');
    }
    
    /**
     * 隐藏加载中遮罩
     */
    function hideLoading() {
        loadingOverlay.classList.add('hidden');
    }
    
    /**
     * 显示错误提示
     */
    function showError(message) {
        errorMessage.textContent = message;
        errorModal.classList.remove('hidden');
    }
    
    /**
     * 显示处理成功结果
     */
    function showSuccess() {
        resultArea.classList.remove('hidden');
        // 3秒后自动隐藏成功提示
        setTimeout(() => {
            resultArea.classList.add('hidden');
        }, 3000);
    }
    
    /**
     * 更新进度条
     */
    function updateProgress(percent, statusMsg, stageIndex) {
        console.log('更新进度:', { percent, statusMsg, stageIndex });
        
        // 保留原来的主进度条更新代码，但实际上不再使用
        if (progressBar) progressBar.style.width = `${percent}%`;
        if (progressText) progressText.textContent = `${percent}%`;
        if (statusText && statusMsg) statusText.textContent = statusMsg;
        
        // 更新浮动进度条
        const floatingProgressBar = document.getElementById('floatingProgressBar');
        const floatingProgressText = document.getElementById('floatingProgressText');
        const floatingStatusText = document.getElementById('floatingStatusText');
        const floatingProgress = document.getElementById('floatingProgress');
        
        // 检查DOM元素是否存在
        console.log('浮动进度条DOM元素:', {
            floatingProgress: !!floatingProgress,
            floatingProgressBar: !!floatingProgressBar,
            floatingProgressText: !!floatingProgressText,
            floatingStatusText: !!floatingStatusText
        });
        
        const stagePills = document.querySelectorAll('.stage-pill');
        console.log('阶段指示器数量:', stagePills.length);
        
        if (floatingProgress) {
            // 显示浮动进度条
            if (percent > 0) {
                floatingProgress.style.display = 'block';
                setTimeout(() => {
                    floatingProgress.classList.add('visible');
                }, 10);
            }
            
            // 更新进度条内容
            if (floatingProgressBar) {
                floatingProgressBar.style.width = `${percent}%`;
            }
            
            if (floatingProgressText) {
                floatingProgressText.textContent = `${percent}%`;
            }
            
            if (floatingStatusText && statusMsg) {
                floatingStatusText.textContent = statusMsg;
            }
            
            // 更新阶段指示器
            if (stageIndex && stagePills && stagePills.length) {
                stagePills.forEach(pill => {
                    const pillStage = parseInt(pill.getAttribute('data-stage'));
                    pill.classList.remove('active', 'completed');
                    
                    if (pillStage < stageIndex) {
                        pill.classList.add('completed');
                    } else if (pillStage === stageIndex) {
                        pill.classList.add('active');
                    }
                });
            }
            
            // 当进度到达100%时，自动隐藏浮动进度条
            if (percent >= 100) {
                setTimeout(() => {
                    floatingProgress.classList.remove('visible');
                    setTimeout(() => {
                        floatingProgress.style.display = 'none';
                    }, 300);
                }, 1500);
            }
        } else {
            console.error('浮动进度条元素不存在');
        }
    }
    
    /**
     * 重置UI状态
     */
    function resetUI() {
        // 添加安全检查，避免访问null元素
        if (progressArea) progressArea.classList.add('hidden');
        if (resultArea) resultArea.classList.add('hidden');
        if (analysisArea) analysisArea.classList.add('hidden');
        if (progressBar) progressBar.style.width = '0%';
        if (progressText) progressText.textContent = '0%';
        if (statusText) statusText.textContent = '正在处理...';
        processedResult = null;
        downloadUrl = null;
    }
    
    /**
     * 更新按钮状态
     */
    function updateButtonState() {
        const hasFile = currentFile !== null;
        processAndDownloadButton.disabled = !hasFile;
    }
    
    /**
     * 格式化文件大小
     */
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    /**
     * 基于原始文件名创建处理后的文件名
     */
    function createProcessedFilename(filename) {
        if (!filename) return 'processed-document_答案在后版.docx';
        
        // 处理带有扩展名的文件名
        if (filename.includes('.')) {
            const lastDotIndex = filename.lastIndexOf('.');
            const nameWithoutExt = filename.substring(0, lastDotIndex);
            const extension = filename.substring(lastDotIndex);
            
            // 检查是否已经添加了后缀
            if (nameWithoutExt.endsWith('_答案在后版')) {
                return filename;
            }
            
            return nameWithoutExt + '_答案在后版' + extension;
        }
        
        // 没有扩展名的文件名
        return filename + '_答案在后版.docx';
    }
    
    // 替换掉之前的formatDownloadFilename函数
    function formatDownloadFilename(serverFilename) {
        // 如果原始文件名存在，使用原始文件名
        if (originalFilename) {
            return createProcessedFilename(originalFilename);
        }
        
        // 否则尝试修复服务器返回的文件名
        // 处理带有扩展名的文件名
        if (serverFilename.includes('.')) {
            const lastDotIndex = serverFilename.lastIndexOf('.');
            const nameWithoutExt = serverFilename.substring(0, lastDotIndex);
            const extension = serverFilename.substring(lastDotIndex);
            
            // 移除 "_答案在后版" 后缀（如果已经是 "filename.docx_答案在后版" 格式）
            const suffix = '_答案在后版';
            if (serverFilename.endsWith(suffix)) {
                return nameWithoutExt + suffix + extension;
            }
            
            // 如果已经是正确格式
            if (nameWithoutExt.endsWith(suffix)) {
                return serverFilename;
            }
            
            return nameWithoutExt + suffix + extension;
        }
        
        // 没有扩展名的文件名
        return serverFilename + '_答案在后版';
    }

    /**
     * 显示服务繁忙信息
     */
    function showServiceBusyMessage(message) {
        // 隐藏进度区域
        progressArea.classList.add('hidden');
        
        // 显示友好的等待提示
        resultArea.classList.remove('hidden');
        resultArea.innerHTML = `
            <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4 mt-4">
                <div class="flex justify-between">
                    <div class="flex">
                        <div class="flex-shrink-0">
                            <svg class="h-5 w-5 text-yellow-400" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 102 0V6zm-1 8a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd" />
                            </svg>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm text-yellow-700 font-medium">系统繁忙</p>
                            <p class="text-sm text-yellow-700 mt-1">${message}</p>
                            <button id="retryDocButton" class="mt-3 px-4 py-2 bg-yellow-200 hover:bg-yellow-300 text-yellow-800 rounded-md text-sm font-medium transition duration-200">
                                稍后重试
                            </button>
                        </div>
                    </div>
                    <div>
                        <button id="closeServiceBusyBtn" class="text-gray-400 hover:text-gray-600 p-1">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            </div>`;
            
        // 添加关闭按钮的点击事件 - 使用setTimeout确保DOM已经渲染完成后再绑定事件
        setTimeout(() => {
            const closeBtn = document.getElementById('closeServiceBusyBtn');
            if (closeBtn) {
                closeBtn.onclick = function() {
                    resultArea.classList.add('hidden');
                };
            }
            
            // 添加重试按钮的点击事件
            const retryBtn = document.getElementById('retryDocButton');
            if (retryBtn) {
                retryBtn.onclick = function() {
                    // 隐藏消息区域
                    resultArea.classList.add('hidden');
                    // 重置按钮状态
                    updateButtonState();
                };
            }
        }, 0);
    }
}); 